package cn.jja8.config.tool;

import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Map;

public class YamlConfig extends Config<YamlConfig>{

    private Yaml getYaml(){
        DumperOptions yamlOptions = new DumperOptions();
        yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        yamlOptions.setAllowUnicode(true);
        return new Yaml(yamlOptions);
    }

    /**
     * 用字符串加载
     * */
    public YamlConfig loadFormString(String str){
        try (StringReader stringReader = new StringReader(str)){
            return load(stringReader);
        }
    }

    /**
     * 从文件加载
     * */
    public YamlConfig load(File file){
        if (!file.isFile()) {
            return this;
        }
        try (FileInputStream fileInputStream = new FileInputStream(file);
             InputStreamReader inputStreamReader =new InputStreamReader(fileInputStream, StandardCharsets.UTF_8)){
            return load(inputStreamReader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 从流加载
     * */
    public YamlConfig load(Reader reader){
        configMap = getYaml().loadAs(reader, Map.class);
        return this;
    }


    /**
     * 保存到流
     * */
    public YamlConfig save(Writer writer){
        getYaml().dump(configMap,writer);
        return this;
    }

    /**
     * 保存到字符串
     */
    public String save(){
        return getYaml().dump(configMap);
    }

    /**
     * 保存到文件
     * */
    public YamlConfig save(File file){
        try (OutputStream outputStream = Files.newOutputStream(file.toPath());
             OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)){
            return save(outputStreamWriter);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
